<template>
  <div class="test-editor">
    <div> <input type="file" @change="selectFile" /> </div>
    <div class="editor-c">
      <Editor v-model="html" />
    </div>
    <div>
      <el-button @click="saveToFile">导出word</el-button>
    </div>
  </div>
</template>
<script setup>
import { Editor } from '@/components/CKEditor'
import { wordblob2html, fileToBlob, word2html } from '@/utils/file'
import { ref } from 'vue'

const html = ref('')

const clearDocxStyle = () => {
  const styles = document.head.querySelectorAll("[name='docx-editor']")
  for (let i = 0; i < styles.length; i++) {
    document.head.removeChild(styles[i])
  }
}

const filePath =
  '/data/upload/%E2%80%9CB-I-G%E2%80%9D%E8%AF%BE%E7%A8%8B%EF%BC%9A%E7%94%B7%E5%AD%A9%E5%A5%B3%E5%AD%A9%EF%BC%8C%E9%98%B3%E5%85%89%E4%B8%8B%E5%B0%BD%E6%83%85%E7%BB%BD%E6%94%BE_20230808121949.docx'

word2html(filePath).then((res) => {
  clearDocxStyle()
  setTimeout(() => {
    html.value = res.querySelector('.docx-wrapper').outerHTML
    const styles = res.querySelectorAll('style')
    for (let i = 0; i < styles.length; i++) {
      styles[i].setAttribute('name', 'docx-editor')
      document.head.appendChild(styles[i])
    }
  }, 200)
})

const selectFile = async (e) => {
  const blob = await fileToBlob(e.target.files[0])
  console.log(blob)
  const res = await wordblob2html(blob)
  console.log(res)
}

const saveToFile = async () => {
  const htmlToDocx = await import('html-to-docx').then((module) => module.default)
  const styles = document.head.querySelectorAll("[name='docx-editor']")
  let styleStr = ''
  styles.forEach((s) => (styleStr += s.outerHTML))
  let content = `
    	 	<!DOCTYPE html><html>
          <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            ${styleStr}
          </head>
          <body>
            ${html.value
              .replaceAll('data:application/octet-stream;base64,', 'data:image/png;base64,')
              .replaceAll('<img ', '<img width="100%" height="200" ')}
          </body>
        </html>`
  console.log(content)
  const blob = await htmlToDocx(content, null, {
    table: { row: { cantSplit: true } },
    footer: true,
    pageNumber: true
  })
  // const blob = new Blob([data], { type: 'text/plain' })
  //const blob = new Blob([data], {type: 'audio/wav'})
  const a = document.createElement('a')
  a.href = URL.createObjectURL(blob)
  const path = filePath
  const paths = path.split('/')
  a.download = paths[paths.length - 1] || '未命名' // 这里填保存成的文件名
  a.click()
  URL.revokeObjectURL(a.href)
}
</script>
<style lang="less">
.test-editor {
  .editor-c {
    height: 600px;
  }
}
</style>
